package com.atguigu.lease.common.aliyunOss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssService {

    @Autowired
    private OSS ossClient;

    @Autowired
    private OssProperties ossProperties;

    /**
     * 上传文件到阿里云OSS
     *
     * @param file 文件
     * @return 文件在OSS中的URL
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + extension;

        // 上传文件
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                ossProperties.getBucketName(),
                fileName,
                file.getInputStream()
        );
        PutObjectResult result = ossClient.putObject(putObjectRequest);

        // 构造文件访问URL
        String url = "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint() + "/" + fileName;
        return url;
    }
}